package com.itheima.java.ai.langchin4j.controller;

import com.itheima.java.ai.langchin4j.config.JwtUtil;
import com.itheima.java.ai.langchin4j.entity.User;
import com.itheima.java.ai.langchin4j.server.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;

import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Tag(name = "用户管理")
@RestController
@RequestMapping("/api/user")
@CrossOrigin(origins = "*")
public class UserController {
    
    // 默认用户策略 - 权限控制移除后使用
    private static final Long DEFAULT_USER_ID = 1L;
    private static final String DEFAULT_USERNAME = "system";
    private static final String DEFAULT_ROLE = "ADMIN";
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private JwtUtil jwtUtil;
    
    @Operation(summary = "用户注册")
    @PostMapping("/register")
    public ResponseEntity<Map<String, Object>> register(@RequestBody User user) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            boolean success = userService.register(user);
            if (success) {
                response.put("success", true);
                response.put("message", "注册成功");
                
                // 生成JWT token
                String token = jwtUtil.generateToken(user.getId(), user.getUsername(), user.getRole().name());
                String refreshToken = jwtUtil.generateRefreshToken(user.getId(), user.getUsername());
                response.put("token", token);
                response.put("refreshToken", refreshToken);
                
                // 返回用户基本信息（不包含密码）
                User userInfo = new User();
                userInfo.setId(user.getId());
                userInfo.setUsername(user.getUsername());
                userInfo.setEmail(user.getEmail());
                userInfo.setRealName(user.getRealName());
                userInfo.setPhone(user.getPhone());
                userInfo.setRole(user.getRole());
                response.put("userInfo", userInfo);
                
                return ResponseEntity.ok(response);
            } else {
                response.put("success", false);
                response.put("message", "注册失败");
                return ResponseEntity.badRequest().body(response);
            }
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    @Operation(summary = "用户登录")
    @PostMapping("/login")
    public ResponseEntity<Map<String, Object>> login(@RequestBody Map<String, String> loginRequest) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String username = loginRequest.get("username");
            String password = loginRequest.get("password");
            
            User user = userService.login(username, password);
            
            response.put("success", true);
            response.put("message", "登录成功");
            
            // 生成JWT token
            String token = jwtUtil.generateToken(user.getId(), user.getUsername(), user.getRole().name());
            String refreshToken = jwtUtil.generateRefreshToken(user.getId(), user.getUsername());
            response.put("token", token);
            response.put("refreshToken", refreshToken);
            
            // 返回用户信息（不包含密码）
            User userInfo = new User();
            userInfo.setId(user.getId());
            userInfo.setUsername(user.getUsername());
            userInfo.setEmail(user.getEmail());
            userInfo.setRealName(user.getRealName());
            userInfo.setPhone(user.getPhone());
            userInfo.setGender(user.getGender());
            userInfo.setBirthDate(user.getBirthDate());
            userInfo.setRole(user.getRole());
            response.put("userInfo", userInfo);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    @Operation(summary = "获取用户信息")
    @GetMapping("/profile")
    public ResponseEntity<Map<String, Object>> getUserProfile(HttpServletRequest request) {
        // 使用默认用户ID - 权限控制已移除
        Long userId = DEFAULT_USER_ID;
        Map<String, Object> response = new HashMap<>();
        
        try {
            User user = userService.getById(userId);
            if (user != null) {
                // 返回用户信息（不包含密码）
                User userInfo = new User();
                userInfo.setId(user.getId());
                userInfo.setUsername(user.getUsername());
                userInfo.setEmail(user.getEmail());
                userInfo.setRealName(user.getRealName());
                userInfo.setPhone(user.getPhone());
                userInfo.setIdCard(user.getIdCard());
                userInfo.setGender(user.getGender());
                userInfo.setBirthDate(user.getBirthDate());
                userInfo.setRole(user.getRole());
                
                response.put("success", true);
                response.put("data", userInfo);
                return ResponseEntity.ok(response);
            } else {
                response.put("success", false);
                response.put("message", "用户不存在");
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    @Operation(summary = "更新用户信息")
    @PutMapping("/profile")
    public ResponseEntity<Map<String, Object>> updateUserProfile(@RequestBody User user, HttpServletRequest request) {
        // 使用默认用户ID - 权限控制已移除
        Long currentUserId = DEFAULT_USER_ID;
        user.setId(currentUserId);
        Map<String, Object> response = new HashMap<>();
        
        try {
            boolean success = userService.updateUserInfo(user);
            if (success) {
                response.put("success", true);
                response.put("message", "更新成功");
                return ResponseEntity.ok(response);
            } else {
                response.put("success", false);
                response.put("message", "更新失败");
                return ResponseEntity.badRequest().body(response);
            }
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
}